package cn.huhaoran.yaoyaolingxian.ui.toolWindow;

import cn.huhaoran.yaoyaolingxian.actions.newNavDestinationPageAnAction;
import cn.huhaoran.yaoyaolingxian.ui.ExportImportBranchByAFileDialog;
import cn.huhaoran.yaoyaolingxian.util.YaoYaoLingXianUtils;
import com.intellij.execution.ExecutionManager;
import com.intellij.execution.ProgramRunnerUtil;
import com.intellij.execution.RunManager;
import com.intellij.execution.RunnerAndConfigurationSettings;
import com.intellij.execution.configurations.*;
import com.intellij.execution.executors.DefaultRunExecutor;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.execution.runners.ExecutionEnvironmentBuilder;
import com.intellij.execution.runners.ProgramRunner;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowFactory;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.terminal.JBTerminalSystemSettingsProviderBase;
import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentFactory;
import com.intellij.ui.content.ContentManager;
import com.jediterm.pty.PtyProcessTtyConnector;
import com.jediterm.terminal.ProcessTtyConnector;
import com.jediterm.terminal.ui.JediTermWidget;
import com.jediterm.terminal.ui.settings.DefaultSettingsProvider;
import com.pty4j.PtyProcess;
import com.pty4j.PtyProcessBuilder;
import git4idea.repo.GitRepository;
import git4idea.repo.GitRepositoryManager;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.List;

public class MyToolWindowFactory implements ToolWindowFactory {

    @Override
    public void createToolWindowContent(Project project, ToolWindow toolWindow) {
        Icon myIcon = IconLoader.getIcon("/icons/pluginIcon16.svg", newNavDestinationPageAnAction.class);
        toolWindow.setIcon(myIcon);
        // 创建工具窗口的内容面板
        ExportImportBranchByAFileDialog exportImportBranchByAFileDialog = new ExportImportBranchByAFileDialog();
        JPanel exportJPanel =exportImportBranchByAFileDialog.getExportJPanel();
        JPanel importJPanel =exportImportBranchByAFileDialog.getImportJPanel();

        //panel.add(new JLabel("Hello, Tool Window!"));

        // 使用新的 API 获取 ContentFactory 实例
        ContentFactory contentFactory = ContentFactory.getInstance();
        Content exportContent = contentFactory.createContent(exportJPanel, "导出本地分支到文件", false);
        Content importContent = contentFactory.createContent(importJPanel, "从本地文件导入分支", false);

        // 将内容添加到工具窗口
        toolWindow.getContentManager().addContent(exportContent);
        toolWindow.getContentManager().addContent(importContent);


        // todo 标签终端功能还需要完善
        JPanel panel = new JPanel();
        JButton button = new JButton("Run Git Command");

        button.addActionListener(e -> {
            // 创建新标签并在当前项目的 Git 仓库目录中执行命令
            createGitCommandTab(toolWindow, project, "git branch");
            //executeInRunWindow(YaoYaoLingXianUtils.getActiveProject(), "git branch");
        });
        panel.add(button);

        //ContentFactory contentFactory = ContentFactory.getInstance();
        Content content = contentFactory.createContent(panel, "测试功能", false);
        toolWindow.getContentManager().addContent(content);
    }

    private void createGitCommandTab(ToolWindow toolWindow, Project project, String command) {
        // 获取当前项目的 Git 仓库目录
        GitRepositoryManager repositoryManager = GitRepositoryManager.getInstance(project);
        List<GitRepository> repositories = repositoryManager.getRepositories();

        if (repositories.isEmpty()) {
            JOptionPane.showMessageDialog(null, "No Git repository found in this project.");
            return;
        }

        String gitRoot = repositories.get(0).getRoot().getPath(); // 获取第一个 Git 仓库的根目录

        try {
            // 检测操作系统并根据系统设置命令解释器
            String os = System.getProperty("os.name").toLowerCase();
            ProcessBuilder processBuilder;

            if (os.contains("win")) {
                // Windows 系统，使用 cmd 或 PowerShell
                processBuilder = new ProcessBuilder("cmd.exe", "/c", command)
                        .directory(new File(gitRoot));
            } else {
                // macOS 或 Linux 系统，使用 bash
                processBuilder = new ProcessBuilder("/bin/bash", "-c", command)
                        .directory(new File(gitRoot));
            }

            // 启动进程执行命令
            Process process = processBuilder.start();


            // 读取和显示命令输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8));
            StringBuilder output = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                output.append(line).append("\n");
            }
            // 此处处理获取到的输出结果
            String result = output.toString();
            System.out.println("Command Output: " + result);
            // 显示输出结果到终端
            JBTerminalSystemSettingsProviderBase settingsProvider = new JBTerminalSystemSettingsProviderBase();
            JediTermWidget terminalWidget = new JediTermWidget(settingsProvider);

            // 创建虚拟终端会话
            //terminalWidget.createTerminalSession().start();

            // 创建新的标签页并将终端组件添加到其中
            JPanel terminalPanel = new JPanel(new BorderLayout());
            terminalPanel.add(terminalWidget.getComponent(), BorderLayout.CENTER);

            ContentFactory contentFactory = ContentFactory.getInstance();
            Content content = contentFactory.createContent(terminalPanel, "执行GIT命令", true);
            // 设置标签页为可关闭
            content.setCloseable(false);
            // 添加锁定/解锁按钮
            JButton lockButton = new JButton("Unlock Tab");
            terminalPanel.add(lockButton, BorderLayout.SOUTH);
            // 锁定/解锁按钮的行为
            lockButton.addActionListener(e -> {
                if (!content.isCloseable()) {
                    // 解锁标签页，允许关闭
                    content.setCloseable(true);
                    lockButton.setText("Lock Tab");
                } else {
                    // 锁定标签页，禁止关闭
                    content.setCloseable(false);
                    lockButton.setText("Unlock Tab");
                }
            });
            ContentManager contentManager = toolWindow.getContentManager();

            contentManager.addContent(content);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 在 IDEA 的终端标签中执行命令
     *
     * @param project 当前的项目
     * @param command 要执行的命令
     */
/*    public static void executeInTerminal(Project project, String command) {
        // 获取终端视图
        TerminalView terminalView = TerminalView.getInstance(project);

        // 创建一个新的终端窗口并获取 ShellTerminalWidget
        ShellTerminalWidget terminalWidget = terminalView.createLocalShellWidget(project.getBasePath(), "My Terminal");

        // 执行命令
        terminalWidget.executeCommand(command);

        // 可选：在关闭项目时自动销毁终端会话
        Disposer.register(project, terminalWidget);
    }*/

    /**
     * 在 IDEA 的 "运行" 标签中执行命令
     *
     * @param project 当前的项目
     * @param command 要执行的命令
     */

/*    public static void executeInRunWindow(Project project, String command) {
        try {
            // 创建 GeneralCommandLine，用于执行命令
            GeneralCommandLine commandLine = new GeneralCommandLine("/bin/bash", "-c", command);  // For Windows use "cmd.exe", "/c", command
            commandLine.setWorkDirectory(project.getBasePath());
            ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(project);
            ToolWindow terminal = toolWindowManager.getToolWindow("Terminal");
            // 使用 ExternalSystemRunConfigurationType
            ExternalSystemRunConfigurationType configurationType = ExternalSystemRunConfigurationType.getInstance();

            // 创建临时运行配置
            RunnerAndConfigurationSettings runSettings = RunManager.getInstance(project).createConfiguration("My Command Run", configurationType.getConfigurationFactories()[0]);

            ExternalSystemRunConfiguration runConfiguration = (ExternalSystemRunConfiguration) runSettings.getConfiguration();
            runConfiguration.setProgramParameters(commandLine.getCommandLineString());

            // 创建 ExecutionEnvironment
            ExecutionEnvironmentBuilder builder = ExecutionEnvironmentBuilder.create(DefaultRunExecutor.getRunExecutorInstance(), runConfiguration);
            ExecutionEnvironment environment = builder.build();

            // 使用 ProgramRunnerUtil 执行命令并显示在运行窗口
            ProgramRunnerUtil.executeConfiguration(environment, false, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/
}
